package com.gp.servlet.v2;

import com.gp.mvcframework.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

public class GPDispatcherServlet extends HttpServlet {

    private Properties contextConfig = new Properties();

    private List<String> classNames = new ArrayList<String>();

    private Map<String , Object> IOC = new HashMap<>();

//    private Map<String , Method> handllerMapping = new HashMap<>();
    //  由map 改为了 list
    private List<HandlerMapping> handlerMapping = new ArrayList<>();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        doDispatch(req, resp);

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2.扫描相关的类
        doScanner(contextConfig.get("scanPackage").toString());

        //3.初始化所有的类的相关实例，并且放在IOC容器中
        doInstance();

        //4.依赖注入
        doAutowired();

        //5.初始化 HandlerMapping
        initHandlerMapping();

        System.out.println(" my spring framework V2 is init.");

    }

    /**
     *  反射调用时的参数类型转换改造
     *
     * @param req
     * @param resp
     */
    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) {

        HandlerMapping handlerMapping = this.getHandler(req);

        if (null == handlerMapping){
            try (PrintWriter writer = resp.getWriter()){
                writer.write("404 Not Found!!!");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Class<?>[] paramTypes = handlerMapping.getParamTypes();
        Object[] paramValues = new Object[paramTypes.length];

        Map<String, String[]> params = req.getParameterMap();
        for (Map.Entry<String, String[]> param : params.entrySet()) {

            String value = Arrays.toString(param.getValue())
                    .replaceAll("\\[|\\]","")
                    .replaceAll("\\s",",");

            if (!handlerMapping.paramIndexMapping.containsKey(param.getKey())){continue;}

            Integer index = handlerMapping.paramIndexMapping.get(param.getKey());
            paramValues[index] = this.convert(paramTypes[index], value);
        }

        if (handlerMapping.paramIndexMapping.containsKey(HttpServletRequest.class.getName())){

            Integer reqIndex = handlerMapping.paramIndexMapping.get(HttpServletRequest.class.getName());
            paramValues[reqIndex] = req;
        }
        if(handlerMapping.paramIndexMapping.containsKey(HttpServletResponse.class.getName())){

            Integer respIndex = handlerMapping.paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[respIndex] = resp;
        }

        try (PrintWriter writer = resp.getWriter()){
            Object returnValue = handlerMapping.method.invoke(handlerMapping.controller, paramValues);

            if (null == returnValue || returnValue instanceof Void){ return;}
            writer.write(returnValue.toString());

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private HandlerMapping getHandler(HttpServletRequest req) {

        if (handlerMapping.isEmpty()) {return null;}

        // 绝对路径
        String url = req.getRequestURI();

        // 处理成相对路径
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath, "").replaceAll("/+","/");

        for (HandlerMapping mapping : handlerMapping) {
            if (mapping.getUrl().equals(url)){
                return mapping;
            }
        }
        return null;
    }

    /**
     *  URL 传递的参数都是 字符串类型的，需要将 String 转为任意类型
     *
     *  spring 定义了一个 convert 接口
     *
     * 类型转换
     * @param type
     * @param value
     * @return
     */
    private Object convert(Class<?> type, String value){
        if(Integer.class == type){
            return Integer.parseInt(value);
        }
        // 策略模式实现 类型转换

        return value;
    }

    private void initHandlerMapping() {

        if (IOC.isEmpty()) return ;

        for (Map.Entry<String, Object> entry : IOC.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();

            if (!(clazz.isAnnotationPresent(GPController.class))) continue;

            String baseUrl = "";
            if(clazz.isAnnotationPresent(GPRequestMapping.class)){
                GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);
                baseUrl = requestMapping.value();
            }

            // 默认获取所有的 public 方法
            for (Method method : clazz.getMethods()) {

                if(!method.isAnnotationPresent(GPRequestMapping.class)) continue;
                GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);
                String url = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");

//                handllerMapping.put(url, method);
                //handlerMapping 有 map 改为 List 实现
                this.handlerMapping.add(new HandlerMapping(url, entry.getValue(), method));

                System.out.println("Mapped :" + url + "," + method);

            }


        }

    }

    private void doAutowired() {

        if(IOC.isEmpty()) return;

        for (Map.Entry<String, Object> entry : IOC.entrySet()){

            // declared 所有的字段 包括 private protected default
            // 正常来说，普通的OOP 变成只能拿到 public 属性
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();

            for (Field field: declaredFields){

                if (!field.isAnnotationPresent(GPAutowired.class)) continue;
                GPAutowired autowired = field.getAnnotation(GPAutowired.class);

                // 用户没有自定义 绑定的 beanName， 默认根据变量类型注入
                // 这里没有对首字母大小的判断
                String beanName = autowired.value().trim();
                if ("".equals(beanName)){
                    beanName = field.getType().getName();
                }

                // 如果是public 以外的修饰符，只要加了 @Autowired 注解，都要强制赋值
                // 反射中称为暴力访问。
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(), IOC.get(beanName));

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void doInstance() {

        //初始化，为 DI 做准备
        if(classNames.isEmpty()) return;
        try {

            for (String className: classNames){
                Class<?> clazz = Class.forName(className);

                if(clazz.isAnnotationPresent(GPController.class)){// 使用的是 GPController 注解

                    Object instance = clazz.newInstance();
                    String beanName = clazz.getSimpleName();
                    IOC.put(toLowerFirstCase(beanName), instance);
                }else if(clazz.isAnnotationPresent(GPService.class)){ // 使用的是 GPService 注解

                    GPService service = clazz.getAnnotation(GPService.class);
                    String beanName = service.value();
                    if("".equals(beanName.trim())){
                        beanName = toLowerFirstCase(clazz.getSimpleName());
                    }

                    Object instance = clazz.newInstance();
                    IOC.put(beanName, instance);

                    // 根究类型复制，如果一个接口有多个实现类  这里就会报出异常，这种情况是会出现的
                    // 可设置实现类是否是默认的实现，或是实现类进行有限级排序
                    for (Class<?> claz :clazz.getInterfaces()){
                        if (IOC.containsKey(claz.getName())){
                            throw new Exception("The “"+claz.getName()+"” has exists!");
                        }
                        IOC.put(claz.getName(), instance);
                    }
                }


            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void doScanner(String scanPackage) {

        URL url = this.getClass().getClassLoader().getResource(File.separator + scanPackage.replace(".", File.separator));

        File classPath = new File(url.getFile());

        for (File file: classPath.listFiles()){
            if(file.isDirectory()){

                doScanner(scanPackage+"."+file.getName());
            }else{
                if(!file.getName().endsWith(".class")){continue;}
                classNames.add(scanPackage+"."+file.getName().replace(".class",""));
            }
        }


    }

    /**
     * 类名首字母小写
     * @param name
     * @return
     */
    private String toLowerFirstCase(String name) {

        // 这里可以判断一下 类的首字母 是否为大写，通过判断 ASCII 数值区间
        char[] chars = name.toCharArray();
        chars[0]+= 32;
        return String.valueOf(chars);

    }


    private void doLoadConfig(String contextConfigLocation) {

        // 自动关闭流，这种能自动关闭的流 都实现了了  AutoCloseable 接口
        // web.xml 中的初始化参数中，指定了配置文件的位置
        // 将 配置文件中的内容 加载到配置类中
        try(InputStream fis = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);) {
            contextConfig.load(fis);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 面向对象的逻辑，
     * 设计模式的最少知道原则
     *
     */
    public class HandlerMapping{
        private String url;
        private Method method;
        private Object controller;
        private Class<?>[] paramTypes;

        // 形参列表
        private Map<String , Integer> paramIndexMapping;

        public HandlerMapping(String url, Object controller, Method method) {
            this.url = url;
            this.method = method;
            this.controller = controller;
            this.paramIndexMapping = new HashMap<>();
            paramTypes = method.getParameterTypes();
            putParamIndexMapping(method);
        }

        /**
         *
         * @param method
         */
        private void putParamIndexMapping(Method method) {

            // 二维数组，第一层是 参数的位置，第二层 每个参数可以允许有多个注解
            Annotation[][] pa = method.getParameterAnnotations();
            for (int i = 0; i < pa.length; i++) {
                for (Annotation annotation : pa[i]) {

                    if(annotation instanceof GPRequestParam){
                        String paramName = ((GPRequestParam) annotation).value();
                        if(null != paramName && !"".equals(paramName.trim())){
                            paramIndexMapping.put(paramName, i);
                        }
                    }
                    
                }
            }

            // request 和 response 对象处理
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {

                Class<?> parameterType = parameterTypes[i];
                if(parameterType == HttpServletRequest.class
                    || parameterType == HttpServletResponse.class){

                    paramIndexMapping.put(parameterType.getName(), i);
                }
            }


        }

        public String getUrl() {
            return url;
        }

        public Method getMethod() {
            return method;
        }

        public Object getController() {
            return controller;
        }

        public Class<?>[] getParamTypes(){
            return paramTypes;
        }
    }
}
